import style from "./styles/global.module.css";

const storageKey = "juejin-publish-ontime/record";
const scheduleTimeStorageKey = "juejin-publish-ontime/timer";
const tasks: {
  [key: string]: number;
} = GM_getValue(storageKey, {});

function inEditor(pathname: string) {
  return /\/editor\/drafts(?:\/|$)/.test(pathname);
}

function getDraftByPath(pathname: string) {
  return pathname.match(/\/editor\/drafts\/\d+(?:\/|$)/)?.[0] || "";
}

function formatDate(dateInstance: Date) {
  const year = dateInstance.getFullYear();
  const month = (dateInstance.getMonth() + 1).toString().padStart(2, "0");
  const date = dateInstance.getDate().toString().padStart(2, "0");
  const hour = dateInstance.getHours().toString().padStart(2, "0");
  const minutes = dateInstance.getMinutes().toString().padStart(2, "0");

  return `${year}-${month}-${date}T${hour}:${minutes}`;
}

function scheduler() {
  const current = new Date().getTime();

  const currentTasks = Object.entries(tasks).filter(([, time]) => {
    return time <= current;
  });
  currentTasks.forEach(([draft]) => {
    delete tasks[draft];
  });

  GM_setValue(storageKey, tasks);

  currentTasks.forEach(([draft]) => {
    GM_notification({
      title: "掘金定时发文提醒",
      text: "可以发布掘金文章了",
      onclick: () => {
        window.open(draft);
      },
    });
  });
  currentTasks.length = 0;

  const scheduleTime = GM_getValue(scheduleTimeStorageKey, 0);
  const duration = 60 * 1000;
  if (scheduleTime + duration < current) {
    GM_setValue(scheduleTimeStorageKey, current);
    setTimeout(() => {
      scheduler();
    }, duration);
  }
}

scheduler();

function mount() {
  const publishBtn = document.querySelector(
    ".markdown-editor > .editor-header > .right-box > .publish-popup"
  );

  if (publishBtn) {
    const popup = document.createElement("div");
    popup.classList.add(style.popup);

    const onTimeBtn = document.createElement("button");
    onTimeBtn.className = "xitu-btn xitu-btn-outline";
    onTimeBtn.textContent =
      getDraftByPath(location.href) in tasks ? "已定时" : "定时发布";

    const timePickerPanel = document.createElement("div");
    timePickerPanel.classList.add(style.panel);

    const dateTimePicker = document.createElement("input");
    dateTimePicker.type = "datetime-local";
    dateTimePicker.classList.add(style.picker);
    const actionBar = document.createElement("div");
    actionBar.classList.add(style.actionBar);
    const confirmBtn = document.createElement("button");
    confirmBtn.className = "xitu-btn";
    confirmBtn.textContent = "确定";
    confirmBtn.addEventListener("click", () => {
      try {
        const selectedTime = dateTimePicker.value;
        const time = new Date(selectedTime).getTime();
        if (!isNaN(time)) {
          const draft = getDraftByPath(location.href);
          if (draft) {
            tasks[draft] = time;
          }
          GM_setValue(storageKey, tasks);
          onTimeBtn.textContent = "已定时";
          timePickerPanel.classList.remove(style.show);
        }
      } catch (e) {}
    });

    const cancelBtn = document.createElement("button");
    cancelBtn.className = "xitu-btn xitu-btn-outline";
    cancelBtn.textContent = "取消";
    cancelBtn.addEventListener("click", () => {
      timePickerPanel.classList.remove(style.show);
    });
    actionBar.appendChild(cancelBtn);
    actionBar.appendChild(confirmBtn);

    timePickerPanel.appendChild(dateTimePicker);
    timePickerPanel.appendChild(actionBar);

    onTimeBtn.addEventListener("click", () => {
      timePickerPanel.classList.toggle(style.show);
      dateTimePicker.min = formatDate(new Date());
      dateTimePicker.value = formatDate(new Date());
    });

    popup.appendChild(onTimeBtn);
    popup.appendChild(timePickerPanel);
    publishBtn.parentElement?.insertBefore(popup, publishBtn);
  } else {
    setTimeout(mount, 1000);
  }
}

export default {
  onLoaded() {
    if (inEditor(location.pathname)) {
      mount();
    }
  },
  onRouteChange(_prev: string, current: string) {
    if (inEditor(current)) {
      mount();
    }
  },
};
